<template>
  <div class="custom_page formSearch">
    <div class="content">
      <!-- 顶部搜索 -->
      <div class="toolbar">
        <!-- 顶部搜索 -->
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="分销员昵称">
            <el-input
              v-model="searchForm.distributorName"
              maxlength="20"
              placeholder="请输入分销员昵称"
            />
          </el-form-item>
          <el-form-item label="分销员手机号">
            <el-input
              v-model="searchForm.distributorPhone"
              maxlength="11"
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item label="加入时间">
            <el-date-picker
              v-model="searchForm.dates"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="分销员等级">
            <el-select
              v-model="searchForm.distributorLevelId"
              placeholder="请选择分销员等级"
            >
              <el-option
                v-for="(item, index) in humenList"
                :key="index"
                :label="item.levelName"
                :value="item.distributorLevelId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button @click="clear">重置</el-button>
            <el-button type="success" @click="add">添加分销员</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--  表格 -->
      <div class="content_table">
        <div class="table">
          <el-table
            v-loading="tableLoading"
            :data="tableData"
            border
            :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
            style="width: 100%"
            class="dataTable"
          >
            >
            <el-table-column prop="distributorName" label="分销员昵称" />
            <el-table-column prop="distributorPhone" label="分销员手机号" />
            <el-table-column prop="inviteesName" label="邀请人" />
            <el-table-column prop="levelName" label="分销员等级" />
            <el-table-column prop="total" label="累计客户" />
            <el-table-column prop="subordinate" label="累计下级" />
            <el-table-column prop="money" label="累计佣金(元 )" />
            <el-table-column label="操作" show-overflow-tooltip>
              <template #default="scope">
                <div class="btnList">
                  <el-button link type="primary" @click="edit(scope.row)">编辑</el-button>
                  <el-button link type="primary" @click="del(scope.row)">清退</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="fenye">
            <el-pagination
              v-model:current-page="searchForm.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="searchForm.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              background
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 分销员弹框 -->
    <el-dialog
      v-model="isVisible.show"
      :title="isVisible.title"
      width="30%"
      center
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="分销员昵称" prop="distributorName">
            <el-input
              v-model="form.distributorName"
              maxlength="20"
              :disabled="isVisible.index === 2"
            />
          </el-form-item>
          <el-form-item label="分销员手机号" prop="distributorPhone">
            <el-input
              v-if="distributorPhoneShow"
              :model-value="hidden(form.distributorPhone, 3, 3)"
              :disabled="isVisible.index === 2"
              maxlength="11"
            />
            <el-input
              v-else
              v-model="form.distributorPhone"
              :disabled="isVisible.index === 2"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="分销员等级" prop="distributorLevelId">
            <el-select
              v-model="form.distributorLevelId"
              placeholder="请选择分销员等级"
            >
              <el-option
                v-for="item in humenList"
                :key="item.distributorLevelId"
                :label="item.levelName"
                :value="item.distributorLevelId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="邀请人" prop="invitees">
            <el-select
              v-model="form.invitees"
              clearable
              placeholder="请选择邀请人"
            >
              <el-option
                v-for="item in inviteList"
                :key="item.distributorId"
                :label="item.distributorName"
                :value="item.distributorId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isVisible.show = false">取消</el-button>
          <el-button type="primary" :loading="addLoading" @click="agreeEn">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 清退弹框 -->
    <el-dialog
      v-model="isVisible.shows"
      :title="isVisible.title"
      center
      :close-on-click-modal="false"
      width="30%"
    >
      <div style="text-align: center">
        <div class="unbindimg">
          <img src="../../../assets/images/tixing.png" alt srcset />
        </div>
        <div class="dialog_content">
          清退之后，用户将失去分销员身份， 下级客户将会解绑关系。确定要清退吗
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isVisible.shows = false">取消</el-button>
          <el-button type="primary" :loading="clearLoading" @click="agreeEn">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import {
  getAllLevel,
  distributorGetAll,
  getAllInvitees,
  distributorAdd,
  distributorGetById,
  distributorUpdate,
  distributorDelete,
} from '@/api/distributor'

const searchForm = ref({
  distributorName: '',
  distributorPhone: '',
  dates: [],
  distributorLevelId: '',
  page: 1,
  pageSize: 10
})
const formRef = ref(null)
const form = ref({
  invitees: '', // 邀请人id
  distributorName: '', // 分销员名称
  distributorPhone: '', // 分销员手机号
  distributorLevelId: '' // 分销员等级id
})
const addLoading = ref(false)
const clearLoading = ref(false)
const isVisible = ref({})
const humenList = ref([])
const total = ref(1)
const tableLoading = ref(false)
const tableData = ref([])
const inviteList = ref([])
const privacyTime = ref(0)
const distributorPhoneShow = ref(false)
const rules = ref({
  distributorName: [
    { required: true, message: '请输入分销员昵称', trigger: 'blur' },
  ],
  distributorPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '请输入正确的手机号码',
    },
  ],
  distributorLevelId: [
    { required: true, message: '请选择分销员等级', trigger: 'change' },
  ],
  invitees: [
    { required: false, message: '请选择邀请人', trigger: 'change' },
  ]
})

onBeforeMount(() => {
  getAll()
  getAllPeo()
  getAllPeos()
  privacyTime.value = localStorage.getItem('privacyTime')
})
const handleSizeChange = (val) => {
  searchForm.value.pageSize = val
  getAll()
}
const handleCurrentChange = (val) => {
  searchForm.value.page = val
  getAll()
}
// 查询
const search = () => {
  total.value = 1
  searchForm.value.page = 1
  getAll()
}
const reset = () => {
  form.value = {
    invitees: '', // 邀请人id
    distributorName: '', // 分销员名称
    distributorPhone: '', // 分销员手机号
    distributorLevelId: '', // 分销员等级id
  }
}
// 添加分销员
const add = () => {
  isVisible.value = {
    show: true,
    title: '添加分销员',
    index: 1,
  }
  distributorPhoneShow.value = false
  reset()
}
// 编辑
const edit = async (row) => {
  distributorPhoneShow.value = true
  const res = await distributorGetById({
    distributorId: row.distributorId,
  })
  if (res.code === '') {
    form.value = res.data
    isVisible.value = {
      show: true,
      title: '编辑分销员',
      index: 2,
    }
  }
}
const agreeEn = async () => {
  await formRef.value.validate( async (valid) => {
    if (valid) {
      if (isVisible.value.index === 1) {
        try {
          addLoading.value = true
          const res = await distributorAdd(form.value)
          if (res.code === '') {
            ElMessage.success('新增成功')
            getAll()
            reset()
            isVisible.value.show = false
          }
        } finally {
          addLoading.value = false
        }
      } else if (isVisible.value.index === 2) {
        try {
          addLoading.value = true
          const res = await distributorUpdate(form.value)
          if (res.code === '') {
            ElMessage.success('编辑成功')
            getAll()
            reset()
            isVisible.value.show = false
          }
        } finally {
          addLoading.value = false
        }
      } else if (isVisible.value.index === 3) {
        try {
          clearLoading.value = true
          const res = await distributorDelete({
            distributorId: isVisible.value.distributorId,
          })
          if (res.code === '') {
            ElMessage.success('清退成功')
            getAll()
            reset()
            isVisible.value.shows = false
          }
        } finally {
          clearLoading.value = false
        }
      }
    } else {
      return false
    }
  })
}
// 清退
const del = (row) => {
  isVisible.value = {
    shows: true,
    title: '清退',
    index: 3,
    distributorId: row.distributorId,
  }
}
// 清除
const clear = () => {
  searchForm.value = {
    orderFormid: '',
    distributorName: '',
    distributorPhone: '',
    dates: [],
    page: 1,
    pageSize: 10,
  }
  getAll()
}
// 初始化查询所有数据
const getAll = async () => {
  try {
    tableLoading.value = true
    const res = await distributorGetAll(searchForm.value)
    tableData.value = res.data.list
    tableData.value.forEach((item) => {
      item.distributorPhone = hidden(item.distributorPhone, 3, 3)
    })
    total.value = res.data.total
  } finally {
    tableLoading.value = false
  }
}
// 初始化查询所有分销员
const getAllPeo = async () => {
  const res = await getAllLevel({})
  humenList.value = res.data
  console.log(res.data)
}
// 初始化查询所有邀请人
const getAllPeos = async () => {
  const res = await getAllInvitees({})
  inviteList.value = res.data
}
// 中间部分
const hidden = (str, frontLen, endLen) => {
  let endLenData = 0
  if (str.length !== 2) {
    endLenData = endLen
  }
  const len = str.length - frontLen - endLenData
  let xing = ''
  for (let i = 0; i < len; i++) {
    xing += '*'
  }
  return (
    str.substring(0, frontLen) +
    xing +
    str.substring(str.length - endLenData)
  )
  // return str
}
</script>

<style lang="scss" scoped>
// .custom_page {
//   padding: 20px 20px 0;
// }
.checkBoxStyle {
  margin-bottom: 20px;
}
.dialog_content {
  width: 275px;
  height: 46px;
  margin: auto;
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #333333;
  line-height: 30px;
  margin-top: 25px;
}
</style>
